$(function(){
	//回车搜索
	$(document).keypress(function(e) {
		//回车键事件
		if(e.which == 13) {
			var searchKeyVal = $("#searchKeyVal").val();
			$("#sync_search_key").val(searchKeyVal);
			$("#searchForm").submit();
		}
	}); 

	// 上拉加载更多
	$(window).on('scroll',function(){
		// 暂时禁用上拉潮品
		return false;
		if($(window).scrollTop()>=$(document).height()-$(window).height()){

			var page_count = $("#sync_page_count").val();
			var current_page = $("#sync_page_num").val();
			if(parseInt(current_page) >= parseInt(page_count)){
				//layer.msg('已经到底了',{time:500});
				return false;
			}
			var params = "requestType=sync";
			$("input[id^='sync_']").each(function(){
				if($(this).attr("pname") == "pageNum"){
					params = params + "&tmpCurrentPage="+(parseInt($(this).val())+1);
				}else{
					params = params + "&"+$(this).attr("pname")+"="+$(this).val();
				}
			});
			// 搜索潮品
			var url = rootPath + "/wx/share/module";
			$.ajax({
				type : "post",
				url : url,
				data : params,
				datatype : "json",
				success : function(jsonObject) {
					var json = $.parseJSON(jsonObject);
					$("#sync_page_num").val(json.currentPage);
					if(json.recordList){
						for(var i = 0 ; i < json.recordList.length; i++){
							var shareInfo = json.recordList[i];
							var headImg = shareInfo.wxHeadImage;
							if (headImg.indexOf('http') < 0) {
								headImg = imgRootURL + headImg + ossImgZoomWX
							}
							var shareInfo_str = "<div class='article' id=''>" +
							"<div class='box1'>" +
							"<div class='pic'>" +
							"<img src='"+ imgRootURL + shareInfo.sharedProductImagePath + ossImgZoomWX +"' onclick='toShareDetailPage("+shareInfo.id+");'>" +
							"</div>" +
							"<div class='item-info'>" +
							"<h2 onclick='toShareDetailPage("+shareInfo.id+");'>"+shareInfo.shareTitle+"</h2>" +
							"<dl>" +
							"<dt>" +
							"<i><img src='"+headImg+"'></i>" +
							"<span>"+shareInfo.userName+"</span>" +
							"</dt>" +
							"<dt>";
							if (shareInfo.isUserLike > 0) {
								shareInfo_str += "<a href='javascriopt:void(0);' class='zan current'>" +
										"<em></em>" +
										"</a>";
							}else {
								shareInfo_str += "<a href='javascriopt:void(0);' onclick='doShareInfoLike(this,"+shareInfo.id+")' class='zan'>" +
										"<em></em>" +
										"</a>";
							}
							shareInfo_str += "<span>"+shareInfo.likeQuantity+"</span>"
							"</dt>" +
							"</dl>" +
							"</div>" +
							"</div>" +
							"</div>";
//							$("#share_info_list").append($(product_str));
							var wallDiv = $("#share_info_list").find(".wall-column")[i%2];
							$(wallDiv).append($(shareInfo_str));
						}
					}
				},
				error : function() {
					layer.msg('查询分享信息失败',{time:1000});
				}
			});
		}
	});
	
	
	// 请登录
	$("#btn_please_login").click(function(){
		window.location.href = rootPath + "/wx/my/toBindAccountPage?goToUrl=%2Fwx%2Findex";
	});

	//关闭端口规格项筛选弹层
	$("#btn_close_product_spec").click(function(){
		$('#goods_editbox').toggle();
	});

	// 异步查询规格项,弹出规格项
	$("a[id='btn_add_to_shoppingcart']").each(function(){
		$(this).click(function(){
			init_add_to_shoppingcart($(this));
		});
	});

	// 减少购买数量
	$("#btn_reduce_buy_num").click(function(){
		var buy_num = $("#v_buy_num").val();
		if(buy_num != 1){
			$("#v_buy_num").val(parseInt(buy_num)-1);
		}
		
	});
	// 增加购买数量
	$("#btn_add_buy_num").click(function(){
		var buy_num = $("#v_buy_num").val();
		$("#v_buy_num").val(parseInt(buy_num)+1);
	});

	// 确认添加到的购物车
	$("#btn_buy_confirm").click(function(){
		
		var buy_num = $("#v_buy_num").val();
		if(!buy_num || buy_num == 0){
			layer.msg('请选择购买数量',{time:1000});
			return false;
		}
		
		// 规格项选择
		var flag = true;
		var spec = [];
		$("div[name='spec_list']").each(function(){
			var spec_name= $(this).find("h3").text();
			var select_li = $(this).next("div.bd").find("label.checked");
			var selected_num = select_li.length;
			if(selected_num == 0){
				layer.msg('请选择'+spec_name,{time:2000});
				flag = false;
			}else{
				select_li.each(function(){
					spec.push({id:$(this).attr("spec_id"),specName:spec_name,specValue:$(this).text()});
				});
			}
		});
		
		if(!flag){
			return false;
		}
		
		$.ajax({
			type : 'POST',
			url : rootPath + "/home/isLogin",
			async : true,
			dataType : 'json',
			success : function(json) {
				console.log("是否登录："+json.code);
				if (json.code == '1') {
					
					
					//立即购买
					var url = rootPath + "/wx/shoppingcart/directAdd";
					var form = $('<form></form>');
				    form.attr('action', url);
				    form.attr('method', 'post');
				    form.attr('target', '_self');
				    form.appendTo("body");
				    form.append($("<input type='hidden' name='addFlag' value='1'/>"));
				    form.append($("<input type='hidden' name='directBuy' value='1'/>"));
				    form.append($("<input type='hidden' name='productId' value='"+$("#v_product_id").val()+"'/>"));
				    form.append($("<input type='hidden' name='specListJson' value='"+JSON.stringify(spec)+"'/>"));
				    form.append($("<input type='hidden' name='buyNum' value='"+buy_num+"'/>"));
				    form.append($("<input type='hidden' name='shareId' value='"+$("#shareInfoId").val()+"'/>"));
				    form.submit();
				} else {
					var index = layer.confirm("您尚未登录，请先登录！",{btn:['去登录','下次再说']},function(){
						//授权登录
						window.location.href = rootPath + "/wx/my/toBindAccountPage?goToUrl=%2Fwx%2Findex";
					},function(){
						layer.close(index);
					});
				}
			}
		});
		
	});
	
});



function initSpecCheck(container , main_product_price){
	container.find('li label').click(function(){
		if($(this).hasClass('checked')){
			$(this).addClass('checked');
		}else{
			$(this).addClass('checked');
			$(this).parent().siblings().find('label').removeClass('checked');
		}
		var spec_price = 0;
		$('.good_sxlist ul li label.checked').each(function(){
			spec_price = spec_price + parseFloat($(this).parent().attr("spec_price"));
		});
		var last_price = spec_price + parseFloat(main_product_price);
		
		container.parent().find("#v_product_price").html("￥<em>"+numberInteger(last_price)+"</em><span>"+numberDecimal(last_price)+"</span>");
	});
}

// initSpecCheck();


// 绑定添加购物车事件
function init_add_to_shoppingcart(this_){
	// 商品名称 价格 从页面上取
	var product_name = this_.closest("h3").find("#product_name").val();
	var product_price_integer = this_.closest("h3").find("#product_price_integer").val();
	var product_price_deciaml = this_.closest("h3").find("#product_price_decimal").val();
	var product_image = this_.closest("h3").find("#product_image").val();
	var product_id = this_.attr("product_id");
	
	var main_product_price = this_.closest("h3").find("#main_product_price").val();
	
	$("#v_product_image").attr("src",imgRootURL+"/"+product_image);
	$("#v_product_name").text(product_name);
	$("#v_product_price").html("￥<em>"+product_price_integer+"</em><span>."+product_price_deciaml+"</span>");
	$("#v_product_id").val(product_id);
	
	var self = this_;
	
	// 查询商品规格项
	// 添加购物车
	var url = rootPath + "/wx/product/listProductSpec";
	var params = {
		productId : product_id
	};
	$.ajax({
		type : "post",
		url : url,
		data : params,
		datatype : "json",
		success : function(json) {
			if(json){
				$("#spec_container").html("");
				var has_spec = json.has_spec;
				if(has_spec == "true"){
					// 商品规格 
					var product_spec = json.product_spec;
					for(var i = 0 ; i < product_spec.length; i++){
						var spec = product_spec[i];
						var spec_value_list = spec.productSpecList;
						
						var spec_value_str = "";
						for(var j = 0; j <spec_value_list.length; j++){
							var spec_value = spec_value_list[j];
							spec_value_str += 
								"<li spec_price=\""+spec_value.specPrice+"\">"+
                        			"<label "+(j == 0 ? "class='checked'" : "")+" spec_id=\""+spec_value.id+"\" >"+spec_value.specValue+"</label>"+
	                        	"</li>";
						}
						
						var product_spec_str = ""+ 
								"<div name=\"spec_list\" class=\"hd\">"+
				            		"<h3>"+spec.specName+"</h3>"+
					            "</div>"+
					            "<div class=\"bd\">"+
					            	"<div class=\"good_sxlist\">"+
					                	"<ul>"+
					                		spec_value_str+
					                    "</ul>"+
					                "</div>"+
					            "</div>";
						$("#spec_container").append($(product_spec_str));
						initSpecCheck($("#spec_container"),main_product_price);
					}
				}
				$('#goods_editbox').toggle();
			}
		},
		error : function() {
			layer.msg('暂时无法查询商品规格项',{time:1000});
		}
	});
}


/**
 * 用户点赞
 */
function doShareInfoLike(this_, shareId){
	var url = rootPath + "/wx/share/doShareInfoLike";
	$.ajax({
		type : 'POST',
		url : rootPath + "/home/isLogin",
		async : true,
		dataType : 'json',
		success : function(json) {
			console.log("是否登录："+json.code);
			if (json.code == '1') {
				$.ajax({
					type : "post",
					url : url,
					data : {shareId: shareId},
					datatype : "json",
					success : function(jsonObject) {
						if (jsonObject.resultCode == '1') {
							$(this_).addClass("current");
							$(this_).removeAttr("onclick");
							var likeNum = parseInt($(this_).closest("dt").find("span").text())+1;
							$(this_).closest("dt").find("span").text(likeNum);
						} else {
							layer.msg('点赞失败',{time:1000});
						}
					},
					error : function() {
						layer.msg('点赞失败',{time:1000});
					}
				});
			} else {
				//授权登录
				window.location.href = rootPath + "/wx/my/toBindAccountPage?goToUrl=%2Fwx%2Findex";
			}
		}
	});
}

/**
 * 跳转至详情页
 * @param id
 */
function toShareDetailPage(id){
	window.location.href = rootPath + "/wx/share/detail?id="+id;
}